//
//  ViewController.m
//  OperationQueueDemo
//
//  Created by hs on 2017/7/14.
//  Copyright © 2017年 jiachen. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setTitle:@"btn1" forState:UIControlStateNormal];
    btn1.frame = CGRectMake(0,0,100,50);
    btn1.center = self.view.center;
  
    [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
//    NSOperation;
//    NSInvocationOperation;
//    NSBlockOperation;
//    NSOperationQueue;
    //创建异步线程的两种方式
   
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)btnAction:(UIButton *)sender{
    
    //NSOperationQueue
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [queue setMaxConcurrentOperationCount:2];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(dealTask) object:nil];
    NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(dealTask) object:nil];
    NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
        
        NSLog(@"blockOperation");
  //      [operation1 cancel];
        [queue setSuspended:YES];
        for (int i = 0; i< 10;i++) {
            
            sleep(5);
            NSLog(@"%d",i);
            if (i == 7) {
            
            }
            
        }
        
    }];
    

    //主线程回调
    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
    //    [operation1 waitUntilFinished];
        NSLog(@"xxxxxxxxxxxxxx");
    }];
    
    [queue addOperationWithBlock:^{
        NSLog(@"xxxxxx");
    }];
    [queue addOperation:blockOperation];
    [queue addOperation:operation];
    [queue addOperation:operation1];
    
    dispatch_apply(5, dispatch_get_global_queue(0,0), ^(size_t index) {
        NSLog(@"xxxxxxxxx%zu",index);
    });
    
}

- (void)dealTask{
    
    NSLog(@"operation1");
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
